#include "CampaignMainWindow.h"
#include "ui_CampaignMainWindow.h"


#include <d20.h>
#include <Campaign.h>



#include <QMessageBox>
#include <QInputDialog>
#include <QTimer>


using namespace d20;



CampaignMainWindow::CampaignMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CampaignMainWindow)
{
    ui->setupUi(this);
    ui->dockWidgetRels->hide();

    installEventFilter(this);
}

CampaignMainWindow::~CampaignMainWindow()
{
    delete ui;
}


void CampaignMainWindow::setCampaign(Campaign *c)
{
    disconnect(this, SLOT(onChanged()));

    m_campaign = c;

    if (m_campaign.isNull()) return;

    ui->xmlPage->setCampaign(m_campaign.data());
    ui->itemTree->setCampaign(m_campaign.data());
    ui->campaignNameLabel->setText(m_campaign->name());

    onChanged();
    connect(m_campaign.data(), SIGNAL(sigChanged()), this, SLOT(onChanged()));
}


Campaign* CampaignMainWindow::campaign() const
{
    return m_campaign.data();
}



void CampaignMainWindow::showXml(bool show)
{
    if (show) ui->stackedWidget->setCurrentWidget(ui->xmlPage);
    else ui->stackedWidget->setCurrentWidget(ui->editPage);
}



void CampaignMainWindow::onChanged()
{
    if (!campaign()) return;

    ui->itemTree->setCurrent(ui->editPage->item());
    ui->campaignNameLabel->setText(campaign()->name());
}



void CampaignMainWindow::createItem(int type, QString name)
{
    if (m_campaign.isNull()) return;

    Item* item = m_campaign->createItem(type, name);
    if (!item)
    {
        QMessageBox::information(this, tr("Error"), tr("Failed to create item!"));
        return;
    }

    ui->itemTree->setCurrent(item);
    ui->editPage->setItem(item);
}


void CampaignMainWindow::on_itemTree_sigItemSelected(Item* item)
{
    if (!item) return;

    ui->editPage->setItem(item);
}

void CampaignMainWindow::renameCampaign()
{
    QString text = QInputDialog::getText(this, tr("Rename Campaign"), QString(), QLineEdit::Normal, ui->campaignNameLabel->text());
    if (text.isEmpty()) return;

    m_campaign->setName(text);
}


void CampaignMainWindow::updateCampaign()
{
    ui->editPage->updateItem();
}


bool CampaignMainWindow::eventFilter(QObject *, QEvent *e)
{
    if (e->type() != QEvent::MouseButtonDblClick) return false;

    QPoint pos = ui->campaignNameLabel->mapFromGlobal(QCursor::pos());
    QRect rect = ui->campaignNameLabel->geometry();
    //QString debug = "%1, %2";
    //QString d1 = debug.arg(pos.x()).arg(pos.y());
    //QString d2 = debug.arg(rect.x()).arg(rect.height());
    //QMessageBox::information(this, tr("Debug"), QString("%1\n%2").arg(d1).arg(d2));

    if (!rect.contains(pos)) return false;

    renameCampaign();
    return true;
}
